﻿using HANS_BackStage.Impl;
using HANS_BackStage.Model.WebModel.Account;
using HANS_BackStageWeb.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using HANS.Utility.Extensions;
using MvcPaging;
using HANS_BackStage.Model.WebModel.Role;
using HANS_BackStage.Model.DbModel;
using HANS.DataBaseTool;
using HANS_Base.Model;
using HANS_Base.Services;
using HANS_BackStage;
using HANS_BackStage.Model;
using HANS_BackStage.Model.WebModel;

namespace HANS_BackStageWeb.Controllers
{
    public class AccountController : CommonController
    {
        // GET: Account
        public ActionResult Index()
        {
            return View();
        }


        #region 管理员
        /// <summary>
        /// 返回管理员列表
        /// </summary>
        /// <param name="pagedListModel"></param>
        /// <returns></returns>
        public ActionResult AdminList(AdminPagedListModel pagedListModel)
        {
            pagedListModel.PagedList = AdminServices.All()
                .Where(a => a.Name.ContainsNoCase(pagedListModel.Keyword) || a.Truename.ContainsNoCase(pagedListModel.Keyword))
                .OrderBy(a => a.Name).ToPagedList(pagedListModel.PageIndex, pagedListModel.Size);
            pagedListModel.QueryParmeter = GetParameterFromQueryString();
            return View(pagedListModel);
        }

        /// <summary>
        /// 创建后台管理员
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult CreateAdmin()
        {
            Backstage_admin model = new Backstage_admin();
            ViewData["AllRoles"] = RoleServices.All();
            ViewData["MyRole"] = Role_PermiServices.GetRoleSelf("");
            ViewData["FaceImag"] = HANS_Base.Services.FileUploadServices.SetFaceIma();
            return View(model);
        }
        /// <summary>
        /// 创建后台管理员
        /// </summary>
        /// <param name="postModel"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult CreateAdmin(Backstage_admin postModel, string Roles)
        {
            JsonResultData result = new JsonResultData();
            result.RunWithTry(item =>
            {
                if (ModelState.IsValid)
                {
                    Msg msg = new Msg();
                    Backstage_admin admin = AdminServices.GetByName(postModel.Name);
                    if (admin.IsNull())
                    {
                        string guid = string.Empty;
                        string[] roles = Roles.Split(',');
                        var face = SaveFile("FaceIma", FileSaveRuleServices.AdminFaceImageSavePath);
                        postModel.Id = guid.NewGuid();
                        postModel.Faceimage = face;
                        postModel.Password = postModel.Password.GetMD5Hash();
                        postModel.Createby = AdminSession.Name;
                        postModel.Createlogindate = DateTime.Now;
                        postModel.Lastlogindate = DateTime.Now;
                        msg = AdminServices.CreateAdmin(postModel);
                        if (msg.Result)
                        {
                            msg = Role_PermiServices.SetRole_Admin(postModel.Id, roles);
                            if (msg.Result)
                            {
                                result.Success = true;
                                result.RedirectUrl = Url.Action("AdminList", "Account");
                                result.AddMessage("添加成功！");
                            }
                            else
                            {
                                result.Success = false;
                                result.AddMessage("添加失败！");
                            }
                        }
                    }
                    else
                    {
                        msg.Result = false;
                        msg.AddMsg("账号已存在");
                        result.Success = false;
                        result.ReloadPage = true;
                    }
                }
                else
                {
                    result.AddModelValidErrorMessage(ModelState);
                }
            });
            return JsonAllowGet(result);
        }

        [HttpGet]
        public ActionResult UpdateAdmin(string Name)
        {
            Backstage_admin admin = AdminServices.GetByName(Name);
            ViewData["AllRoles"] = RoleServices.All();
            ViewData["MyRole"] = Role_PermiServices.GetRoleSelf(admin.Id);
            return View(admin);
        }
        /// <summary>
        /// 修改管理员
        /// </summary>
        /// <param name="postModel"></param>
        /// <param name="Roles"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult UpdateAdmin(Backstage_admin postModel, string Roles)
        {
            JsonResultData result = new JsonResultData();
            result.RunWithTry(item =>
            {
                ModelState.Remove("Password");
                if (ModelState.IsValid)
                {
                    Msg msg = new Msg();
                    Backstage_admin admin = AdminServices.GetByName(postModel.Name);
                    if (admin.IsNotNull())
                    {
                        string[] roles = Roles.Split(',');
                        admin.Nickname = postModel.Nickname;
                        admin.Truename = postModel.Truename;
                        admin.Sex = postModel.Sex;
                        admin.Age = postModel.Age;
                        msg = AdminServices.UpdateAdmin(admin);
                        if (msg.Result)
                        {
                            msg = Role_PermiServices.DeleteRole_Admin(admin.Id);
                            if (msg.Result)
                            {
                                if (!string.IsNullOrWhiteSpace(Roles))
                                {
                                    msg = Role_PermiServices.SetRole_Admin(admin.Id, roles);
                                }
                                if (msg.Result)
                                {
                                    result.Success = true;
                                    result.RedirectUrl = Url.Action("AdminList", "Account");
                                    result.AddMessage("修改成功！");
                                }
                                else
                                {
                                    result.Success = false;
                                    result.AddMessage("修改失败！");
                                }
                            }
                        }
                    }
                    else
                    {
                        result.Success = false;
                        result.ReloadPage = true;
                        result.AddMessage(msg.ToString());
                    }
                }
                else
                {
                    result.AddModelValidErrorMessage(ModelState);
                }
            });
            return JsonAllowGet(result);
        }
        /// <summary>
        /// 删除管理员
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public JsonResult DeleteAdmin(string name)
        {

            JsonResultData result = new JsonResultData();
            result.RunWithTry(item =>
            {
                Msg msg = new Msg();
                msg = AdminServices.DeleteAdmin(name);
                result.Success = msg.Result;
                result.AddMessage(msg.ToString());
                result.ReloadPage = true;
            });
            return JsonAllowGet(result);
        }


        [HttpGet]
        public ActionResult MyProfile() {
            Backstage_admin admin = AdminSession.adminEntity;
           
            ViewData["FaceImag"] = HANS_Base.Services.FileUploadServices.SetFaceIma(admin.Faceimage);

            return View(admin);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult MyProfile(ProfileModel postmodel) {

            JsonResultData result = new JsonResultData();
            result.RunWithTry(item =>
            {
                if (postmodel.NewPassword.IsNullOrWhiteSpace())
                {
                    ModelState.Remove("Password");
                }
                if (ModelState.IsValid)
                {
                    var adminEntity = AdminSession.adminEntity;
                    var face = SaveFile("FaceIma", FileSaveRuleServices.AdminFaceImageSavePath);
                    if (face.IsNotEmpty())
                    {
                        adminEntity.Faceimage = face;
                        
                    }
                    adminEntity.Nickname = postmodel.Nickname;
                    adminEntity.Truename = postmodel.Truename;
                    adminEntity.Sex = postmodel.Sex;
                    adminEntity.Age = postmodel.Age;
                    if (!AdminServices.SetIfChangePassword(adminEntity, postmodel.Password, postmodel.NewPassword))
                    {
                        result.Success = false;
                    }
                    else
                    {
                        AdminServices.UpdateAdmin(adminEntity);

                        result.RedirectUrl = Url.Action("MyProfile");
                        result.AddSuccessMessage("保存成功！");
                    }

                }
                else
                {
                    result.AddModelValidErrorMessage(ModelState);
                }
            });
            return Json(result);
        }

        #endregion

        #region 角色
        /// <summary>
        /// 返回角色列表
        /// </summary>
        /// <param name="pagedListMoel"></param>
        /// <returns></returns>
        public ActionResult RoleList(RolePagedListModel pagedListMoel)
        {
            pagedListMoel.PagedList = RoleServices.All()
                .Where(r => r.Rolename.ContainsNoCase(pagedListMoel.Keyword))
                .OrderBy(r => r.Rolename).ToPagedList(pagedListMoel.PageIndex, pagedListMoel.Size);
            return View(pagedListMoel);
        }

        /// <summary>
        /// 创建角色
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult CreateRole()
        {
            string[] roleArray = new string[] { };
            Backstage_role role = new Backstage_role();
            ViewBag.PermissionJsonTree = BuildPermissionTreeViewModel(Role_PermiServices.GetAllPermissions().Where(p => p.Parentid == "" || p.Parentid == null).ToList(),
              roleArray).ToJson(JsonExtensions.PropertyNaming.CamelCase);
            return View(role);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult CreateRole(Backstage_role role, string PermissionId)
        {
            JsonResultData result = new JsonResultData();
            result
                .RunWithTry(item =>
                {
                    if (ModelState.IsValid)
                    {
                        string guid = "";
                        Msg msg = new Msg();
                        string[] permissionIdArr = PermissionId.IsNullOrWhiteSpace()
                                               ? new string[0]
                                               : PermissionId.Split(',');
                        var permissionList = Role_PermiServices.GetAllPermissions().Where(p => permissionIdArr.Contains(p.Id)).ToList();

                        role.Id = guid.NewGuid();
                        role.Createby = AdminSession.Name;
                        role.Createdate = DateTime.Now;
                        msg = RoleServices.Insert(permissionList, role);
                        if (msg.Result)
                        {
                            result.Success = msg.Result;
                            result.AddMessage(msg.ToString());
                            result.RedirectUrl = Url.Action("RoleList", "Account");
                        }
                        else
                        {
                            result.Success = msg.Result;
                            result.AddMessage(msg.ToString());
                        }
                    }
                    else
                    {
                        result.AddModelValidErrorMessage(ModelState);
                    }

                });


            return Json(result);
        }

        /// <summary>
        /// 修改角色
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult UpdateRole(string id)
        {
            string[] roleArray = new string[] { };
            Backstage_role role = RoleServices.GetEntityById(id);
            ViewBag.PermissionJsonTree = BuildPermissionTreeViewModel(Role_PermiServices.GetAllPermissions().Where(p => p.Parentid == "" || p.Parentid == null).ToList(),
              Role_PermiServices.GetPermissions(id).ToArray()).ToJson(JsonExtensions.PropertyNaming.CamelCase);
            ViewBag.Role_Admin = AdminServices.GetAdminByRole(id);
            return View(role);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult UpdateRole(Backstage_role postmodel, string PermissionId)
        {
            JsonResultData result = new JsonResultData();
            result
                .RunWithTry(item =>
                {
                    if (ModelState.IsValid)
                    {
                        Backstage_role role = RoleServices.GetEntityById(postmodel.Id);
                        if (role.IsNotNull())
                        {
                            Msg msg = new Msg();
                            string[] permissionIdArr = PermissionId.IsNullOrWhiteSpace()
                                                   ? new string[0]
                                                   : PermissionId.Split(',');
                            var permissionList = Role_PermiServices.GetAllPermissions().Where(p => permissionIdArr.Contains(p.Id)).ToList();
                            role.Rolename = postmodel.Rolename;
                            role.Description = postmodel.Description;
                            msg = Role_PermiServices.DelteRolePermissionByRoleId(role.Id);

                            msg = RoleServices.Update(permissionList, role);
                            if (msg.Result)
                            {
                                result.Success = msg.Result;
                                result.AddMessage(msg.ToString());
                                result.RedirectUrl = Url.Action("RoleList", "Account");
                            }
                            else
                            {
                                result.Success = msg.Result;
                                result.AddMessage(msg.ToString());
                            }
                        }
                        else
                        {
                            result.Success = false;
                            result.AddMessage("角色可能被删除了");
                        }

                    }
                    else
                    {
                        result.AddModelValidErrorMessage(ModelState);
                    }

                });


            return Json(result);
        }


        /// <summary>
        /// 删除角色
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public JsonResult DeleteRole(string id)
        {
            JsonResultData result = new JsonResultData();
            result.RunWithTry(item =>
            {
                Msg msg = new Msg();
                msg = RoleServices.DelteRoleById(id);
                if (msg.Result)
                {
                    result.AddSuccessMessage(msg.ToString());
                    result.ReloadPage = true;

                }
                else
                {
                    result.Success = false;
                    result.AddMessage(msg.ToString());
                }
            });

            return JsonAllowGet(result);
        }

        /// <summary>
        /// 移除某个管理员的角色
        /// </summary>
        /// <param name="adminId"></param>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public JsonResult DeleteAdminRole(string adminId, string roleId)
        {
            JsonResultData result = new JsonResultData();
            result.RunWithTry(item =>
            {
                Msg msg = new Msg();
                msg = Role_PermiServices.DeleteRole_Admin(adminId, roleId);
                if (msg.Result)
                {
                    result.AddSuccessMessage("移除成功");
                    result.ReloadPage = true;
                }
                else
                {
                    result.Success = false;
                    result.AddMessage(msg.ToString());
                }
            });
            return JsonAllowGet(result);
        }
        #endregion

        #region 权限

        /// <summary>
        /// 角色列表
        /// </summary>
        /// <returns></returns>
        public ActionResult Permissionlist()
        {

            return View(Role_PermiServices.GetAllPermissions().Where(p => p.Parentid == null).OrderBy(p => p.Ordernum).ToList());
        }

        /// <summary>
        /// 创建权限
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult CreatePermission()
        {
            Backstage_permission permission = new Backstage_permission();
            var permissionDropdownLostItems = GetPermissionDropdownListItems(Role_PermiServices.GetAllPermissions().Where(p => p.Parentid == null && p.Id != null).ToList(), "", null);
            permissionDropdownLostItems.Insert(0, new SelectListItem { Text = "无", Value = "" });
            ViewBag.PermissionSelectItems = permissionDropdownLostItems;
            return View(permission);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult CreatePermission(Backstage_permission postmodel)
        {
            JsonResultData result = new JsonResultData();
            result.RunWithTry(item =>
            {
                if (ModelState.IsValid)
                {
                    Msg msg = new Msg();
                    string guiid = "";
                    postmodel.Id = guiid.NewGuid();
                    postmodel.Createby = AdminSession.Name;
                    postmodel.Createdate = DateTime.Now;
                    msg = PermissionServices.Add(postmodel);
                    if (msg.Result)
                    {
                        result.AddSuccessMessage(msg.ToString());
                        result.RedirectUrl = Url.Action("Permissionlist", "Account");
                    }
                    else
                    {
                        result.Success = msg.Result;
                        result.AddMessage(msg.ToString());
                    }
                }
                else
                {
                    result.AddModelValidErrorMessage(ModelState);
                }
            });
            return Json(result);
        }

        /// <summary>
        /// 更新权限
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult UpdatePermission(string id)
        {

            Backstage_permission model = PermissionServices.GetEntityById(id);
            if (model.IsNull())
            {
                return Redirect(Url.Action("Permissionlist", "Account"));
            }
            var permissionDropdownLostItems = GetPermissionDropdownListItems(Role_PermiServices.GetAllPermissions().Where(p => p.Parentid == null && p.Id != null).ToList(), "", id);
            permissionDropdownLostItems.Insert(0, new SelectListItem { Text = "无", Value = "" });
            ViewBag.PermissionSelectItems = permissionDropdownLostItems;
            return View(model);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult UpdatePermission(Backstage_permission postmodel)
        {
            JsonResultData result = new JsonResultData();
            result.RunWithTry(item =>
            {
                if (ModelState.IsValid)
                {
                    Msg msg = new Msg();
                    Backstage_permission model = PermissionServices.GetEntityById(postmodel.Id);
                    if (model.IsNotNull())
                    {
                        model.Permissionname = postmodel.Permissionname;
                        model.Description = postmodel.Description;
                        model.Ismenu = postmodel.Ismenu;
                        model.Parentid = postmodel.Parentid;
                        model.Ordernum = postmodel.Ordernum;
                        model.Icon_url = postmodel.Icon_url;
                        postmodel.Controller = postmodel.Controller;
                        model.Action = postmodel.Action;
                        model.Area = postmodel.Area;
                        model.Url = postmodel.Url;
                        msg = PermissionServices.Update(model);
                        if (msg.Result)
                        {
                            result.AddSuccessMessage(msg.ToString());
                            result.RedirectUrl = Url.Action("Permissionlist", "Account");
                        }
                        else
                        {
                            result.Success = msg.Result;
                            result.AddMessage(msg.ToString());
                        }
                    }
                    else
                    {
                        result.Success = false;
                        result.AddMessage("权限不存在！");
                        result.RedirectUrl = Url.Action("Permissionlist", "Account");
                    } 
                }
                else
                {
                    result.AddModelValidErrorMessage(ModelState);
                }
            });
            return Json(result);
        }

        /// <summary>
        /// 删除权限
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult DeletePermission(string id) {
            JsonResultData result = new JsonResultData();
            result.RunWithTry(item=> {

                Backstage_permission permission = PermissionServices.GetEntityById(id);
                if (permission.IsNotNull())
                {
                    Msg msg = new Msg();
                    msg = PermissionServices.HandleDeletePermission(permission);
                    if (msg.Result)
                    {
                        result.AddSuccessMessage("删除成功");

                    }
                    else
                    {
                        result.Success = msg.Result;
                        result.AddMessage(msg.ToString());
                    }
                    result.RedirectUrl = Url.Action("Permissionlist", "Account");
                }
                else
                {
                    result.Success = false;
                    result.AddMessage("权限不存在！");
                    result.RedirectUrl = Url.Action("Permissionlist", "Account");
                }
            });
            return JsonAllowGet(result);
        }

        /// <summary>
        /// 保存权限树的子父关系及其顺序
        /// </summary>
        /// <param name="orderInfo"></param>
        /// <returns></returns>
        public ActionResult SavePermissionOrder(string orderInfo) {
            JsonResultData result = new JsonResultData();
            result.RunWithTry(item=> {
                var nestableOrderInfo =
                    orderInfo.ToObject<List<NestableNote>>(JsonExtensions.PropertyNaming.CamelCase);
                var newPermissions = SetPermissionRelation(nestableOrderInfo, Role_PermiServices.GetAllPermissions());
                result.Success = true;
                result.RedirectUrl = Url.Action("Permissionlist");
                result.AddMessage("保存成功！");
            });
            return JsonAllowGet(result);
        }


        #endregion

        /// <summary>
        /// 重新构建权限树
        /// </summary>
        /// <param name="nestableOrderInfo"></param>
        /// <param name="list"></param>
        /// <returns></returns>
        private List<Backstage_permission> SetPermissionRelation(List<NestableNote> nestableOrderInfo, List<Backstage_permission> list, string id = "")
        {

            List<Backstage_permission> result = new List<Backstage_permission>();
            if (nestableOrderInfo.IsNotEmpty())
            {
                int order = 1;
                foreach (var item in nestableOrderInfo)
                {
                    var tmpPermission = list.FirstOrDefault(p => p.Id == item.id);
                    if (tmpPermission.IsNotNull())
                    {
                        tmpPermission.Ordernum = order++;
                        if (id.IsNotNullAndNotWhiteSpace() && nestableOrderInfo.Count > 0)
                        {
                            tmpPermission.Parentid = id;
                        }
                        else
                        {
                            tmpPermission.Parentid = null;
                        }
                        SetPermissionRelation(item.children, list, item.id);
                        PermissionServices.UpdateParentANDOrdernum(tmpPermission);
                        result.Add(tmpPermission);
                    }
                }
            }
            return result;
        }

        /// <summary>
        /// 构建权限树
        /// </summary>
        private List<TreeViewNote> BuildPermissionTreeViewModel(List<Backstage_permission> permissions, string[] hasPermissionIds = null)
        {
            if (permissions == null || permissions.Count() == 0)
            {
                return null;
            }

            List<TreeViewNote> result = new List<TreeViewNote>();
            foreach (var permission in permissions)
            {
                var note = new TreeViewNote();
                note.Text = permission.Permissionname;
                note.Nodes = BuildPermissionTreeViewModel(Role_PermiServices.GetPerChildrenList(permission.Id), hasPermissionIds);
                note.ServerId = permission.Id;
                note.State = new TreeViewNoteStatus() { Checked = hasPermissionIds.Contains(permission.Id) };
                //{
                //    Text = permission.Permissionname,
                //    Nodes = BuildPermissionTreeViewModel(Role_PermiServices.GetPerChildrenList(permission.Id), hasPermissionIds),
                //    ServerId = permission.Id,
                //    State = new TreeViewNoteStatus() { Checked = hasPermissionIds.Contains(permission.Id) }
                //};
                result.Add(note);
            }
            return result;
        }

        /// <summary>
        /// 生成权限下拉框的selectitem
        /// </summary>
        /// <param name="permissions"></param>
        /// <param name="strOccuy"></param>
        /// <param name="currenPermissionId"></param>
        /// <returns></returns>
        private List<SelectListItem> GetPermissionDropdownListItems(List<Backstage_permission> permissions, string strOccuy = "", string currenPermissionId = "")
        {
            var result = new List<SelectListItem>();
            if (permissions.IsNotEmpty())
            {
                permissions.ForEach(p =>
                {
                    if (p.Id != currenPermissionId)
                    {
                        result.Add(new SelectListItem
                        {
                            Text = strOccuy + p.Permissionname,
                            Value = p.Id
                        });
                        result.AddRange(GetPermissionDropdownListItems(Role_PermiServices.GetPerChildrenList(p.Id), strOccuy + "---------", currenPermissionId));

                    }
                });
            }
            return result;
        }


    }
}